<template>
    <div class="outer-order-page">
        <el-button type="primary" @click="saveAll">修改</el-button>
        <!-- 基本信息部分 -->
        <br/><br/>
        <el-card title="基本信息">
            <el-form 
                :model="form" 
                label-width="120px" 
                ref="formRef" 
                :rules="rules"
            >
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="生产工序名称" prop="processName">
                            <el-input v-model="form.processName" required></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="生产工序编号" prop="processNumber">
                            <el-input placeholder="自动生成" disabled v-model="form.processNumber"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="生产工序类别">
                            <el-select v-model="form.processType" placeholder="请选择" required>
                                <el-option label="设备生产工序" value="设备生产工序"></el-option>
                                <el-option label="食品生产工序" value="食品生产工序"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="产能主体" label-width="140px">
                            <el-radio-group v-model="form.capacityBody" required>
                                <el-radio :label="false">设备</el-radio>
                                <el-radio :label="true">人员</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="*工序负责人" prop="processPerson">
                            <el-input
                                v-model="form.processPerson"
                                :readonly="form.ourRepresentativesInfoFilled"
                                required
                            >
                                <template #suffix>
                                    <el-button size="mini" @click="openOurRepresentativesDialog">
                                        <i class="el-icon-search"></i>
                                    </el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="制单人员">
                            <el-input v-model="form.documentMakers" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="制单日期">
                            <el-date-picker v-model="form.documentDate" type="date" placeholder="选择日期" disabled></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="16">
                        <el-form-item label="备注">
                            <el-input type="textarea" v-model="form.remark"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        <!-- 设备清单 -->
        <el-card title="设备清单">
            <div class="table-operations">
                <el-button type="primary" size="small" @click="addProductRow">增行</el-button>
                <el-button size="small" @click="deleteProductRow">删行</el-button>
            </div>
            <el-table 
                :data="productList" 
                border 
                style="width: 100%" 
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="50px" v-model="multipleSelection.product"></el-table-column>
                <el-table-column label="序号" width="60px" type="index"></el-table-column>
                <el-table-column label="产品名称">
                    <template #default="{ row }">
                        <el-input
                            v-model="row.equipmentName"
                            :readonly="row.productInfoFilled"
                        >
                            <template #suffix>
                                <el-button size="mini" @click="openProductNameDialog(row)">
                                    <i class="el-icon-search"></i>
                                </el-button>
                            </template>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column label="规格型号">
                    <template #default="{ row }">
                        <el-input v-model="row.specificationsModels" :disabled="row.productInfoFilled"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="设备数量">
                    <template #default="scope">
                        <el-input v-model="scope.row.equipmentNum"></el-input>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 人员清单 -->
        <el-card title="人员清单">
            <div class="table-operations">
                <el-button type="primary" size="small" @click="addPersonnelRow">增行</el-button>
                <el-button size="small" @click="deletePersonnelRow">删行</el-button>
            </div>
            <el-table 
                :data="personnelList" 
                border 
                style="width: 100%" 
                @selection-change="handlePersonnelSelectionChange"
            >
                <el-table-column type="selection" width="50px" v-model="multipleSelection.personnel"></el-table-column>
                <el-table-column label="序号" width="60px" type="index"></el-table-column>
                <el-table-column label="人员岗位">
                    <template #default="{ row }">
                        <el-input
                            v-model="row.personnelPositions"
                            :readonly="row.productInfoFilled"
                        >
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column label="定额能力">
                    <template #default="{ row }">
                        <el-input v-model="row.quorumCapacity" :disabled="row.productInfoFilled"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="作业人数">
                    <template #default="scope">
                        <el-input v-model="scope.row.numberWorkers"></el-input>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 我方代表选择对话框 -->
        <el-dialog
            v-model="ourRepresentativesDialogVisible"
            width="500px"
            title="我方代表选择"
            append-to-body
        >
            <el-table
                :data="ourRepresentativesList"
                highlight-current-row
                border
                size="small"
                @current-change="handleOurRepresentativesChange"
            >
                <el-table-column type="index" label="序号" />
                <el-table-column property="userName" label="代表姓名" />
                <el-table-column property="depmentName" label="部门" />
                <el-table-column property="roleName" label="职位" />
            </el-table>
            <template #footer>
                <el-button @click="ourRepresentativesDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="pickOurRepresentatives">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { write, read } from '@/axios/axiosHelper';
import { useCounterStore } from '@/stores/counter'
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();
const store = useCounterStore();

// 表单验证规则
const rules = reactive({
    processName: [{ required: true, message: '请输入生产工序名称', trigger: 'blur' }],
    processType: [{ required: true, message: '请选择生产工序类别', trigger: 'change' }],
    capacityBody: [{ required: true, message: '请选择产能主体', trigger: 'change' }],
    processPerson: [{ required: true, message: '请输入工序负责人', trigger: 'blur' }]
});

// 基本信息表单数据
const form = ref({
    processId: route.query.processId,
    processName: "",
    processNumber: "",
    processType: "",
    capacityBody: false, 
    processPerson: "",
    ourRepresentativesInfoFilled: false, 
    documentMakers: "admin",
    documentDate: new Date(),
    remark: "",
    ordersId: 0,
});

// 设备清单数据
const productList = ref([]);
// 人员清单数据
const personnelList = ref([]);

// 表单ref
const formRef = ref(null);

// 选中行管理
const multipleSelection = ref({
    product: [],
    personnel: []
});

const handleSelectionChange = (val) => {
    multipleSelection.value.product = val;
};

const handlePersonnelSelectionChange = (val) => {
    multipleSelection.value.personnel = val;
};

// 设备清单增行方法
const addProductRow = () => {
    productList.value.push({
        equipmentId: null,
        equipmentName: "",
        specificationsModels: "",
        equipmentNum: 0,
        processId: form.value.processId
    });
    console.log('Added row to productList:', productList.value);
    nextTick(() => {
        console.log('After nextTick, productList:', productList.value);
    });
};

// 人员清单增行方法
const addPersonnelRow = () => {
    personnelList.value.push({
        personnelId: null,
        personnelPositions: "",
        quorumCapacity: "",
        numberWorkers: 0,
        processId: form.value.processId
    });
    console.log('Added row to personnelList:', personnelList.value);
    nextTick(() => {
        console.log('After nextTick, personnelList:', personnelList.value);
    });
};

// 设备清单删行方法
const deleteProductRow = () => {
    const selection = multipleSelection.value.product;
    if (selection.length > 0) {
        productList.value = productList.value.filter(row => 
            !selection.includes(row)
        );
        ElMessage.success('设备清单删除成功');
    } else {
        ElMessage.warning('请先选择要删除的设备清单行');
    }
};

// 人员清单删行方法
const deletePersonnelRow = () => {
    const selection = multipleSelection.value.personnel;
    if (selection.length > 0) {
        personnelList.value = personnelList.value.filter(row => 
            !selection.includes(row)
        );
        ElMessage.success('人员清单删除成功');
    } else {
        ElMessage.warning('请先选择要删除的人员清单行');
    }
};

// 修改主表数据
const updateMainTable = async () => {
    try {
        const response = await write.post('w-write/api/Process/UpdateProcess', form.value);
        if (response.data.code === 100) {
            ElMessage.success('主表数据修改成功');
        } else {
            ElMessage.error(`主表数据修改失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('修改主表数据发生错误:', error);
        ElMessage.error('修改主表数据发生错误，请检查网络或联系管理员');
    }
};

// 修改设备表数据
const updateDetailTable = async (row) => {
    try {
        const dataToSend = { 
            ...row,
            processId: form.value.processId,
            equipmentId: row.equipmentId
        };
        console.log('提交的设备明细数据:', dataToSend);
        let response;
        if (row.equipmentId) {
            // 有 equipmentId 则为更新操作
            response = await write.post('w-write/api/Process/UpdatedEquipment', dataToSend);
        } else {
            // 无 equipmentId 则为新增操作
            response = await write.post('w-write/api/Process/AddEquipment', dataToSend);
        }
        if (response.data.code === 100) {
            row.isSaved = true;
            ElMessage.success('设备明细数据修改成功');
        } else {
            ElMessage.error(`设备明细 ${row.equipmentName} 修改失败：${response.data.message}`);
        }
    } catch (error) {
        console.error(`修改设备明细 ${row.equipmentName} 发生错误:`, error);
        ElMessage.error(`修改设备明细 ${row.equipmentName} 发生错误，请检查网络或联系管理员`);
    }
};

// 修改人员表数据
const updatePersonnelTable = async (row) => {
    try {
        const dataToSend = { 
            ...row,
            processId: form.value.processId,
            personnelId: row.personnelId
        };
        console.log('提交的人员明细数据:', dataToSend);
        let response;
        if (row.personnelId) {
            // 有 personnelId 则为更新操作
            response = await write.post('w-write/api/Process/UpdatedPersonnel', dataToSend);
        } else {
            // 无 personnelId 则为新增操作
            response = await write.post('w-write/api/Process/AddPersonnel', dataToSend);
        }
        if (response.data.code === 100) {
            row.isSaved = true;
            ElMessage.success('人员明细数据修改成功');
        } else {
            ElMessage.error(`人员明细 ${row.personnelPositions} 修改失败：${response.data.message}`);
        }
    } catch (error) {
        console.error(`修改人员明细 ${row.personnelPositions} 发生错误:`, error);
        ElMessage.error(`修改人员明细 ${row.personnelPositions} 发生错误，请检查网络或联系管理员`);
    }
};

// 修改主表单和明细
const saveAll = async () => {
    if (formRef.value) {
        const isValid = await formRef.value.validate();
        if (isValid) {
            await updateMainTable();
            const updateProductPromises = productList.value.map(row => updateDetailTable(row));
            await Promise.all(updateProductPromises);
            const updatePersonnelPromises = personnelList.value.map(row => updatePersonnelTable(row));
            await Promise.all(updatePersonnelPromises);
        }
    }
};

// 我方代表列表
const ourRepresentativesList = ref([]);
const currentOurRepresentative = ref(null);
const ourRepresentativesDialogVisible = ref(false);

// 获取基础数据
const fetchBaseData = () =>{
    read.get('read/api/Depment/GetDepUserRole')
      .then(res => ourRepresentativesList.value = res.data.data || [])
      .catch(error => {
            ElMessage.error('加载我方代表失败');
            console.error(error);
        });
}

// 打开工序负责人对话框
const openOurRepresentativesDialog = () => {
    if (ourRepresentativesList.value.length === 0) {
        ElMessage.warning('工序负责人数据加载中，请稍后重试');
        return;
    }
    ourRepresentativesDialogVisible.value = true;
};

// 处理工序负责人行选中
const handleOurRepresentativesChange = (val) => {
    currentOurRepresentative.value = val;
};

// 选择工序负责人并填充数据
const pickOurRepresentatives = () => {
    if (currentOurRepresentative.value) {
        form.value.processPerson = currentOurRepresentative.value.userName;
        form.value.ourRepresentativesInfoFilled = true;
        ourRepresentativesDialogVisible.value = false;
    } else {
        ElMessage.warning('请选择一个我方代表');
    }
};

// 通用获取数据方法
const getDataById = async (url, id) => {
    try {
        const response = await read.get(url, {
            params: {
                processId: id
            }
        });
        return response.data.data;
    } catch (error) {
        ElMessage.error('获取数据失败，请检查网络或联系管理员');
        console.error(error);
        return [];
    }
};

// 生命周期钩子
onMounted(async () => {
    await fetchBaseData();
    const processId = route.query.processId;
    const processData = await getDataById('w-read/api/Process/GetBYIdProcess', processId);
    form.value = processData[0] || form.value;

    const equipmentData = await getDataById('w-read/api/Process/GetBYIdEquipment', processId);
    productList.value = equipmentData.map(item => ({
        equipmentId: item.equipmentId,
        equipmentName: item.equipmentName,
        specificationsModels: item.specificationsModels,
        equipmentNum: item.equipmentNum,
        processId: item.processId
    }));

    const personnelData = await getDataById('w-read/api/Process/GetBYIdPersonnel', processId);
    personnelList.value = personnelData.map(item => ({
        personnelId: item.personnelId,
        personnelPositions: item.personnelPositions,
        quorumCapacity: item.quorumCapacity,
        numberWorkers: item.numberWorkers,
        processId: item.processId
    }));
});
</script>

<style scoped>
.outer-order-page {
    padding: 20px;
}

.table-operations {
    margin: 10px 0 20px;
    display: flex;
    gap: 8px;
}

.el-form-item {
    margin-bottom: 12px;
}

.el-table {
    margin-top: 15px;
}

.el-input__append {
    padding-right: 8px;
}
</style>    